//
//  LoginForgetPasswordController.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/3/6.
//  Copyright © 2025 考拉🐨. All rights reserved.
//

//  忘记密码
import UIKit
import JFPopup
import SwiftyUserDefaults
import Localize_Swift
import JKSwiftExtension
import FinAuthLiveV5Detect

private let totalSecond: Int = 60

class LoginForgetPasswordController: BaseViewController {
    
    @IBOutlet weak var titleLabel: UILabel!
    
    // 选择国家区号
    @IBOutlet weak var countryImageView: UIImageView!
    @IBOutlet weak var countryCodeLabel: UILabel!
    private var areaCodeModel: AreaCodeModel = AreaCodeModel.default {
        didSet {
            // 中国 不显示邮箱
            captchaView.isHidden = areaCodeModel.id != 0
        }
    }
    
    // 请输入手机号
    @IBOutlet weak var mobileTextField: UITextField!
    
    // 设置新密码
    @IBOutlet weak var setNewPasswordTitleLabel: UILabel!
    @IBOutlet weak var setNewPasswordTextField: UITextField!
    
    // 确认新密码
    @IBOutlet weak var repeatNewPasswordTitleLabel: UILabel!
    @IBOutlet weak var repeatNewPasswordTextField: UITextField!
    
    // 验证码
    @IBOutlet weak var captchaView: UIView!
    @IBOutlet weak var captchaTitleLabel: UILabel!
    @IBOutlet weak var captchaTextField: UITextField!
    // 获取验证码
    @IBOutlet weak var captchaButton: UIButton!
    
    // 协议内容
    @IBOutlet weak var agreementLabel: UILabel!
    @IBOutlet weak var userAgreementButton: UIButton!
    
    // 注册
    @IBOutlet weak var registerButton: UIButton!
    // 提示
    @IBOutlet weak var customerServiceLabel: UILabel!
    
    
    private lazy var areaCodeView: LoginAreaCodeView = {
        let areaCodeView = LoginAreaCodeView.loadFromNib()
        return areaCodeView
    }()
    
    private var timer: Timer?
    // true: 正在获取验证码, false: 发送已结束
    private var isSendingCode: Bool = false
    // true: 同意协议
    private var isAgree: Bool {
        userAgreementButton.isSelected
    }
    // 获取验证码倒计时秒数
    var second: Int = 0 {
        didSet {
            captchaTextField.placeholder = "请输入短信验证码".localized(.login)
            if second >= totalSecond || second <= 0 {
                captchaButton.setTitle("获取验证码".localized(.login), for: .normal)
                
            } else {
                captchaButton.setTitle("\(second)s", for: .normal)
            }
        }
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
        initNav()
        updateLanguageAction()
    }
    
    // 更新语言
    override func updateLanguageAction() {
        
        titleLabel.text = "忘记密码".localized(.login)
        registerButton.setTitle("修 改".localized(.login), for: .normal)
        
        mobileTextField.placeholder = "请输入手机号".localized(.login)
        
        setNewPasswordTitleLabel.text = "设置新密码".localized(.login)
        setNewPasswordTextField.placeholder = "请输入密码".localized(.login)
        
        repeatNewPasswordTitleLabel.text = "确认新密码".localized(.login)
        repeatNewPasswordTextField.placeholder = "请输入密码".localized(.login)
        
        captchaTitleLabel.text = "验证码".localized(.login)
        captchaTextField.placeholder = "请输入短信验证码".localized(.login)
        
        captchaButton.setTitle("获取验证码".localized(.login), for: .normal)
        
        let text = NSMutableAttributedString(string: "阅读并同意《GLUZ用户服务协议和隐私政策》".localized(.login))
        text.color(UIColor(hex: "16C186"))
        text.color(UIColor(hex: "333333"), range: text.string.inRange(of: "阅读并同意".localized(.login)).first!)
        text.font(.systemFont(ofSize: 12))
        agreementLabel.attributedText = text
        
        do {
            customerServiceLabel.isUserInteractionEnabled = true
            customerServiceLabel.sg.addTapGesture(self, #selector(showTelphoneAction))
            
            let text = NSMutableAttributedString(string: "若您长时间未收到短信验证码可联系客服".localized(.login))
            text.color("#333333")
            text.color(.themeColor, range: text.string.inRange(of: "联系客服".localized(.login)).first!)
            text.font(.systemFont(ofSize: 14, weight: .medium))
            customerServiceLabel.attributedText = text
        }
        
        view.layoutIfNeeded()
    }
    
    deinit {
        xLog("deinit -- \(self.className)")
        //        stopTimer()
    }
    
    
    // 切换国家区号
    @IBAction func changeCountryAction(_ sender: UIButton) {
        // 复制分享内容
        areaCodeView.list = AreaCodeModel.dataSources()
        // 弹框
        popup.bottomSheet(enableDrag: false) {
            areaCodeView
        }
    }
    
    // 获取短信验证码
    @IBAction func getSMSAction(_ sender: Any) {
        getSMS()
    }
    
    // 勾选用户协议
    @IBAction func agreementAction(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
    }
    
    @IBAction func registerAction(_ sender: Any) {
        view.endEditing(true)
        
        if mobileTextField.text!.isEmpty {
            YLHUD.showMessage("请输入手机号".localized(.login))
            return
        }
        
        if !String.checkMobile(id: areaCodeModel.id, mobile: mobileTextField.text!) {
            YLHUD.showMessage("请输入正确的手机号".localized(.login))
            return
        }
        
        if setNewPasswordTextField.text!.isEmpty {
            YLHUD.showMessage("请输入密码".localized(.login))
            return
        }
        
        if setNewPasswordTextField.text!.count < 8 {
            YLHUD.showMessage("请输入 8 位以上的密码".localized(.login))
            return
        }
        
        if setNewPasswordTextField.text! != repeatNewPasswordTextField.text {
            YLHUD.showMessage("两次密码不一致".localized(.login))
            return
        }
        
        if areaCodeModel.id != 0 {
            if !isAgree {
                YLAlert(
                    controller: self,
                    title: "提示".localized(),
                    message: "阅读并同意《GLUZ用户服务协议和隐私政策》".localized(.login),
                    actionTitles: ["同意".localized()],
                    cancelTitle: "拒绝".localized(),
                    cancelStyle: .destructive
                ) { [self] action, index in
                    userAgreementButton.isSelected = true
                    xLog("人脸识别")
                    checkPermissionStatus()
                }
                return
            }
            xLog("人脸识别")
            checkPermissionStatus()
            return
        }
        
        if captchaTextField.text!.isEmpty {
            YLHUD.showMessage("请输入短信验证码".localized(.login))
            return
        }
        
        if !isAgree {
            YLAlert(
                controller: self,
                title: "提示".localized(),
                message: "阅读并同意《GLUZ用户服务协议和隐私政策》".localized(.login),
                actionTitles: ["同意".localized()],
                cancelTitle: "拒绝".localized(),
                cancelStyle: .destructive
            ) { [self] action, index in
                userAgreementButton.isSelected = true
                requestForgetPassword()
            }
            return
        }
        
        requestForgetPassword()
        
    }
    
    
    /// 人脸认证
    func faceAuthAction() {
        YLRequest.request(FinAuthAPI.token(type: 2, mobile: mobileTextField.text!)) { result in
            switch result {
            case .success(let res):
                let dataDictionary = res.dataDictionary
                xLog(dataDictionary)
                guard let token = dataDictionary["biz_token"] as? String else {
                    return
                }
                xLog("token : \(token)")
                let config = FinAuthLiveV5DetectInitConfigItem()
                config.phoneVertical = FinAuthLiveV5DetectPhoneVerticalTypeDisable
                // 设置语言
                config.languageType = LanguageManager.isLanguageZH ? FinAuthLiveV5DetectLanguageTypeCh : FinAuthLiveV5DetectLanguageTypeRu
                config.hostURL = "https://api.yljz.com"
                xLog("活体检测SDK初始化开始（可以加loading动画）")
                YLHUD.showLottie()
                FinAuthLiveV5DetectManager.faceLive(withBizToken: token, configInfo: config, extraData: nil, startCallBack: { error, extraOutDict in
                    xLog("活体检测SDK初始化结束（可以将loading动画隐藏）")
                    YLHUD.hideHUD()
                    if let err = error, err.errorCode != FinAuthLiveV5DetectErrorTypeOK {
                        xLog("初始化失败，失败原因：\(err.errorMessage),错误码：\(err.errorCode)")
                        return
                    }
                    xLog("初始化成功，开始进行活体检测。检测页面准备展开")
                    
                }, detectVC: self) { error, bizTokenStr, extraOutDict in
                    xLog("活体检测完成")
                    if let err = error, err.errorCode != FinAuthLiveV5DetectErrorTypeOK {
                        xLog("检测失败，失败原因：\(err.errorMessage),错误码：\(err.errorCode)")
                        return
                    }
                    xLog("检测成功")
                    YLHUD.showLottie()
                    YLRequest.request(FinAuthAPI.liveness(token: token, mobile: self.mobileTextField.text!)) { [self] result in
                        switch result {
                        case .success(let res):
                            let dataDictionary = res.dataDictionary
                            // xLog("活体验证 \(dataDictionary)")
                            let resultCode = dataDictionary["result_code"] as! Int
                            if resultCode == 1000 {
                                xLog("code: \(resultCode) 活体验证通过")
                                let images = dataDictionary["images"] as! [String: Any]
                                let baseImg = dataDictionary["baseImg"] as? String ?? ""
                                var base64Str = ""
                                if !baseImg.isEmpty {
                                    // 由原来的人脸图片
                                    base64Str = baseImg
                                } else {
                                    let image_best = images["image_best"] as? String ?? ""
                                    base64Str = image_best
                                    // 保存活体人脸
                                    YLRequest.request(FinAuthAPI.uploadFaceFile(mobile: mobileTextField.text!, imageBase64: image_best))
                                }
                                
                                if let image = base64Str.base64ToImage, let imageData = image.jpegData(compressionQuality: 1) {
                                    xLog("base64Str count: \(base64Str.count)")
                                    xLog("imageData: \(imageData)")
                                    YLRequest.request(FinAuthAPI.contrast(mobile: mobileTextField.text!, token: token, imageData: imageData)) { [self] result in
                                        switch result {
                                        case .success(let res):
                                            let dataDictionary = res.dataDictionary
                                            xLog(dataDictionary)
                                            xLog("对比 ========[\(dataDictionary)")
                                            let resultCode = dataDictionary["result_code"] as! Int
                                            if resultCode == 1000 {
                                                xLog("code: \(resultCode) 比对通过")
                                                self.requestForgetPassword()
                                            } else {
                                                xLog(" code: \(resultCode) SDK活体图像采集失败")
                                                YLHUD.showMessage("活体对比失败")
                                            }
                                            
                                        case .failure(let err):
                                            YLHUD.showHint(.error, err.errMsg)
                                        }
                                    }
                                } else {
                                    xLog("base64Str count: \(base64Str.count)")
                                }
                                
                            } else if resultCode == 4100 {
                                xLog(" code: \(resultCode) 云端活体判断未通过")
                                YLHUD.showHint(.error, "云端活体判断未通过".localized(.login))
                            } else if resultCode == 4200 {
                                xLog(" code: \(resultCode) SDK活体图像采集失败")
                                YLHUD.showHint(.error, "SDK活体图像采集失败".localized(.login))
                            }
                            
                        case .failure(let err):
                            let dataDictionary = err.dataDictionary
                            xLog("dataDictionary \(dataDictionary as NSDictionary)")
                            let name = dataDictionary["name"] as? String
                            let nameRu = dataDictionary["name_ru"] as? String
                            
                            YLHUD.showMessage(LanguageManager.currentLanguageToText(name, nameRu))
                        }
                    }
                } dismissCallBack: {
                    xLog("活体检测流程结束。检测页面收起。")
                }
            case .failure(let err):
                let dataDictionary = err.dataDictionary
                xLog("dataDictionary \(dataDictionary as NSDictionary)")
                let name = dataDictionary["name"] as? String
                let nameRu = dataDictionary["name_ru"] as? String
                
                YLHUD.showMessage(LanguageManager.currentLanguageToText(name, nameRu))
            }
        }
    }
}

// MARK: - private
private extension LoginForgetPasswordController {
    func initUI() {
        
        registerButton.backgroundColor = .gradient(colors: [
            UIColor(hex: "#278AFF"),
            UIColor(hex: "#66D6E2")
        ], rect: CGRect(x: 0, y: 0, width: xScreenW - 48, height: 48))
        registerButton.addRoundedCorners(radius: 24)
        
        userAgreementButton.touchExpand = 20
        agreementLabel.isUserInteractionEnabled = true
        agreementLabel.sg.addTapGesture(self, #selector(goToAgreementAction))
        
        areaCodeView.cancelBlock = {
            self.popup.dismissPopup()
        }
        
        areaCodeView.didSelectedBlock = { [self] model in
            countryImageView.image = model.image.toImage
            countryCodeLabel.text = "+" + model.code
            areaCodeModel = model
            popup.dismissPopup()
        }
    }
    
    
    func initNav() {
        // 设置初始导航栏透明度
        vhl_navBarBackgroundAlpha = 0
    }
}

// MARK: - 响应事件
private extension LoginForgetPasswordController {
    
    @objc func showTelphoneAction() {
        YLHUD.showLottie()
        YLRequest.request(LoginAPI.customerMobiles) { [self] result in
            switch result {
            case .success(let res):
                YLHUD.hideHUD()
                let dataArray = res.dataArray
                let arr = JsonUtil.modelsFromArray(dataArray, CustomerMobileModel.self)
                if arr.count > 0 {
                    
                    let alerController = UIAlertController(title: "联系客服".localized(.login), message: nil, preferredStyle: .actionSheet)
                    
                    let cancelAction = UIAlertAction(title: "取消".localized(), style: .cancel)
                    alerController.addAction(cancelAction)
                    
                    for model in arr {
                        let countryName = model.country == "zh" ? "中国".localized() : "俄罗斯".localized()
                        let title = countryName + " " + model.tel
                        let action = UIAlertAction(title: title, style: .default) { action in
                            let actionTile = action.title!
                            let tel = String(actionTile.split(separator: " ").last!)
                            JKGlobalTools.callPhone(phoneNumber: tel) { isSuccess in }
                        }
                        alerController.addAction(action)
                    }
                    
                    present(alerController, animated: true)
                    
                }
                
            case .failure(let err):
                YLHUD.showHint(.error, err.errMsg)
            }
        }
        
        
    }
    
    /// 获取验证码
    func getSMS() {
        
        if mobileTextField.text!.isEmpty {
            YLHUD.showMessage("请输入手机号".localized(.login))
            return
        }
        
        if !String.checkMobile(id: areaCodeModel.id, mobile: mobileTextField.text!) {
            YLHUD.showMessage("请输入正确的手机号".localized(.login))
            return
        }
        
        let target = LoginAPI.getSMS(areaCode: areaCodeModel.code, mobile: mobileTextField.text!, event: "resetpwd", email: "111@qq.com")
        YLRequest.request(target) { [self] result in
            switch result {
            case .success(let res):
                let dataDictionary = res.dataDictionary
                xLog(dataDictionary)
                let name = dataDictionary["name"] as? String
                let nameRu = dataDictionary["name_ru"] as? String
                
                YLHUD.showMessage(LanguageManager.currentLanguageToText(name, nameRu))
                
                captchaTextField.becomeFirstResponder()
                initTimer()
                
            case .failure(let err):
                let dataDictionary = err.dataDictionary
                xLog("dataDictionary \(dataDictionary as NSDictionary)")
                let name = dataDictionary["name"] as? String
                let nameRu = dataDictionary["name_ru"] as? String
                
                YLHUD.showMessage(LanguageManager.currentLanguageToText(name, nameRu))
            }
        }
    }
    
    func checkPermissionStatus() {
        PermissionManager.shared.checkPermissionStatus(.camera) { status in
            xLog("相机权限状态: \(status.description)")
            if status == .notDetermined {
                // 2. 请求单个权限
                PermissionManager.shared.requestPermission(.camera) { status in
                    if status == .authorized {
                        xLog("相机权限已授权")
                        self.faceAuthAction()
                        
                    } else {
                        xLog("相机权限未授权，原因: \(status.description)")
                    }
                }
                
            } else if status == .authorized {
                self.faceAuthAction()
                
            } else if status == .denied {
                let alerController = UIAlertController(title: "提示".localized(), message: "请打开系统设置中\"隐私->相机\"，允许访问您的相机。".localized())
                let cancelAction = UIAlertAction(title: "取消".localized(), style: .cancel) { _ in }
                alerController.addAction(cancelAction)
                alerController.addAction(UIAlertAction(title: "设置".localized(), style: .default) { action in
                    PermissionManager.shared.openAppSettings()
                })
                self.present(alerController)
            }
        }
    }
    
    private func requestForgetPassword() {
        let target = LoginAPI.resetPassword(captcha: captchaTextField.text!, mobile: mobileTextField.text!, password: setNewPasswordTextField.text!, country: areaCodeModel.id)
        YLRequest.request(target) { [self] result in
            switch result {
            case .success(let res):
                
                let dataDictionary = res.dataDictionary
                xLog(dataDictionary)
                let name = dataDictionary["name"] as? String
                let nameRu = dataDictionary["name_ru"] as? String
                
                YLHUD.showMessage(LanguageManager.currentLanguageToText(name, nameRu)) {
                    self.push(LoginForgetPasswordSuccessController())
                }
                
            case .failure(let err):
                let dataDictionary = err.dataDictionary
                xLog("dataDictionary \(dataDictionary as NSDictionary)")
                let name = dataDictionary["name"] as? String
                let nameRu = dataDictionary["name_ru"] as? String
                
                
                YLHUD.showMessage(LanguageManager.currentLanguageToText(name, nameRu))
            }
        }
    }
    
    // MARK: - 初始化定时器
    /// 初始化定时器
    func initTimer() {
        captchaButton.isEnabled = false
        second = totalSecond
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
        if let curTimer: Timer = timer {
            RunLoop.main.add(curTimer, forMode: .common)
        }
        timer?.fire()
    }
    
    // 定时器action
    @objc func timerAction() {
        second = second - 1
        if second <= 0 {
            stopTimer()
            captchaButton.isEnabled = true
            captchaTextField.placeholder = "请输入短信验证码".localized(.login)
            captchaTextField.textContentType = .oneTimeCode
        }
    }
    
    // 停止定时
    func stopTimer() {
        if timer != nil {
            second = 0
            timer?.invalidate()
            timer = nil
        }
    }
    
    @objc func goToAgreementAction() {
        view.endEditing(true)
        push(BaseWebViewController(url: H5UrlManager.privacyUrl(type: "隐私政策"), displaysWebViewTitle: false, isNavBarHide: true))
    }
}
